// 网关配置的前缀
var account_server = "/accountSer"

// let userId = "200031"
// let userName = "YANGRANT"
let userId = ""
let userName = ""

let UUID = "";
let oneLevelNum = 0;
// 输入情况判断
var company_value = "", company_correct = false;
var level_value = "", level_correct = false;
var startData_value = ""
var endData_value = "", endData_correct = false;
var photo_value = "", photo_correct = false;

let Authorization = "";
let refreshToken = "";

// 加载页面时读取后台的 ip
window.onload = function () {
    let accountStatus = $("#accountStatus").html();
    if(accountStatus !== "正常"){
        $("#forbidden").removeAttr("hidden");
    }

    let authorities = $("#authorities").html();
    unauthorized_2(authorities, "createAdvertisement");

    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        account_server = data.accountServer;
    });
    UUID = createUUID();
    $("#uuid").val(UUID);
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")
    userId = $("#userId").html();
    userName = $("#userName").html();
    getOneLevel()
    getAdvLevel();

}

$('#submit').click(function (argument) {
    $.ajax({
        type: "PUT",
        async: false,
        url: account_server + "/account/advertise",
        headers: {
            "Content-Type": "application/json",
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: JSON.stringify({
            "level": level_value,
            "companyName": company_value,
            "startDate": startData_value,
            "endDate": endData_value,
            "optionId": userId,
            "optionName": userName,
            "photoId": UUID,
        }),
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg, function () {
                });

                // 提交完后，重置初始值
                $("#company").val("");
                $("#startData").val("");
                $("#endData").val("");

                $("input[name='photo']").val("");
                $(".create-photo-left").css("background", "#99999969");
                $("#photo-logo *").removeAttr("hidden");

                // 提交完后，设置按钮为不可提交
                change_but_status(false);

            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg, function () {
                });
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
})

// 获得 广告等级
function getAdvLevel() {
    let $list = $("#levelList .list");
    let $mySelect = $("#levelList .mySelect");
    $.ajax({
        type: "get",
        async: false,
        url: account_server + "/account/advLevel",
        success: function (data) {
            console.log("广告等级");

            // 如果为空
            if (data.datas.length <= 0) {
                $mySelect.empty();
                $mySelect.append(
                    "<option>暂无数据</option>"
                );
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas, function (i, item) {
                if (item.value === "一级" && oneLevelNum >= 2){
                    $list.append(
                        "<li data-value='' class='option' disabled='disabled'>一级广告数量已达上限</li>"
                    );
                }else {
                    if (i === 1) {
                        $('#levelList .current').html(item.value);
                    }
                    $list.append(
                        "<li data-value='" + item.value + "' class='option'>" + item.value + "</li>"
                    );
                }
            });
        },
        error: function (err) {
            $mySelect.empty();
            $mySelect.append(
                "<option>暂无数据</option>"
            );
        }

    });
}
// 获得 广告等级
function getOneLevel() {
    $.ajax({
        type: "get",
        async: false,
        url: account_server + "/account/advertise",
        data: {
            currentPage: 1,
            level: "一级",
        },
        success: function (data) {
            console.log("一级广告个数");

            oneLevelNum = data.datas.records.length;
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    });
}

// 上传照片 部分
$("input[name='photo']").change(function (event) {
    // 获取图片元素
    var ele = event.target;

    if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(ele.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
    }

    var files = ele.files;
    if (files && files.length <= 0) {
        alert("出错了，请重新上传。")
    }

    var file = files[0];
    // 获取目前上传的文件
    console.log("上传了照片");

    var path = URL.createObjectURL(file);
    $(".create-photo-left").css("background-image", "url(" + path + ")")
        .css("background-repeat", "no-repeat")
        .css('background-size', '100% 100%');
    $("#photo-logo *").hide();


    // 将文件传到后端
    $('#uploadPhoto').ajaxSubmit({
        datatype: 'json',
        success: function (res) {
            cocoMessage.info(2000, "图片上传成功", function () {
            });
        },
        error: function (res) {
            cocoMessage.error(2000, "图片上传出错，请重试", function () {
            });
        }
    });
});

// 合作开始日期
$("#startData").datetimepicker({
    language: 'zh-CN',
    format: 'yyyy-mm-dd hh:ii',
    weekStart: 1,
    todayBtn: 1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 4,
    minView: 0,
    forceParse: 0,
    hours12: false,
}).on('changeDate',function(ev){
    var startData=$("#startData").val();
    $("#endData").datetimepicker('setStartDate',startData);
    $("#startData").datetimepicker('hide');
});
// 合作截至日期
$("#endData").datetimepicker({
    language: 'zh-CN',
    format: 'yyyy-mm-dd hh:ii',
    weekStart: 1,
    todayBtn: 1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 4,
    minView: 0,
    forceParse: 0,
    hours12: false,
}).on('changeDate',function(ev){
    var endData=$("#endData").val();
    $("#startData").datetimepicker('setEndDate',endData);
    $("#endData").datetimepicker('hide');
});

// isSubmit : 是否 可以 提交
function change_but_status(isSubmit) {
    if (isSubmit) {// 可以提交
        $("#submit").attr('disabled', false);
        $("#submit").css('background-color', '#1dae0e');
    } else {// 不可提交
        $("#submit").attr('disabled', true);
        $("#submit").css('background-color', '#808080c2');
    }
}

$("#company").change(function () {
    company_value = $(this).val();
    if (company_value === "") {
        $("#error_company").html("企业名不能为空");
        company_correct = false;
    } else {
        $("#error_company").html("");
        company_correct = true;
    }
    change_but_status(company_correct
        && level_correct
        && endData_correct
        && photo_correct);
})

function click_level() {
    level_value = $('#levelList .current').html();
    if (level_value === "" || level_value === "一级广告数量已达上限") {
        $("#error_level").html("优先级不能为空");
        level_correct = false;
    } else {
        $("#error_level").html("");
        level_correct = true;
    }
    change_but_status(company_correct
        && level_correct
        && endData_correct
        && photo_correct);
}

$("#startData").change(function () {
    startData_value = $(this).val();
    if (startData_value === "") {
        $("#error_endData").html("日期不能为空");
        endData_correct = false;
    } else {
        $("#error_endData").html("");
        endData_correct = true;
    }
    change_but_status(company_correct
        && level_correct
        && endData_correct
        && photo_correct);
})

$("#endData").change(function () {
    endData_value = $(this).val();
    if (endData_value === "") {
        $("#error_endData").html("日期不能为空");
        endData_correct = false;
    } else {
        $("#error_endData").html("");
        endData_correct = true;
    }
    change_but_status(company_correct
        && level_correct
        && endData_correct
        && photo_correct);
})

$(".create-photo-left").change(function () {
    photo_value = $(".create-photo-left").css("background-image")
    if (photo_value === "none") {
        $("#error_photo").html("广告图片不能为空");
        photo_correct = false;
    } else {
        $("#error_photo").html("");
        photo_correct = true;
    }
    change_but_status(company_correct
        && level_correct
        && endData_correct
        && photo_correct);
})

function random () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
function createUUID() {
    return (random() + random() + "-" + random() + "-" + random() + "-" + random() + random());
};
